const { db } = require("../../db/db2");
const moment = require("moment");
const util = require("util");
const redis = require("/redis/redisClient.js");

async function LikePin(req, res) {
  const PinId = req.body.PinId;
  let UserId = Number(req.params.username);
  const likeKey = `Pin:${PinId}:users`; //沸点点赞用户
  const likeCountKey = `Pin:${PinId}:like_count`; //沸点点赞数

  //检查用户是否已经点赞
  const isLiked = await redis.sismember(likeKey, UserId);

  if (isLiked === 1) {
    // 用户已经点赞,执行取消点赞
    await unLikeArticle(UserId, PinId);
  } else {
    //如果redis没查到，查询数据库用户是否点赞
    const checkLikeQuery =
      "SELECT * FROM PinLike WHERE PinId = ? AND UserId = ?";
    const [results] = await db.promise().query(checkLikeQuery, [PinId, UserId]);

    if (results.length > 0) {
      //用户已经点赞,证明redis数据没有与数据库一致，执行同步数据到redis
    } else {
      //用户未点赞
      //将点赞记录保存到 Redis 中
      const transaction = redis.multi();
      transaction.sadd(likeKey, UserId); // 用户点赞记录
      transaction.incr(likeCountKey); // 文章点赞数增加
      await transaction.exec();
    }
  }
}

// 取消点赞
async function unLikeArticle(userId, articleId) {
  const userLikedKey = `Pin:${userId}:users`;
  const articleLikesKey = `Pin:${articleId}:like_count`;

  // 2. 用户取消点赞
  const transaction = redis.multi();
  transaction.srem(userLikedKey, articleId); // 移除用户点赞记录
  transaction.decr(articleLikesKey); // 文章点赞数减少
  await transaction.exec();
}
module.exports = { LikePin };
